import {createStore} from 'vuex'
import { nanoid } from 'nanoid'
import dayjs from "dayjs";
import md5 from "crypto-js/md5";
import sha512 from 'crypto-js/sha512'
import * as DataPersistence from "@/utils/dataPersistence";
import sha256 from "crypto-js/sha256";
import {aesDecrypt} from "@/utils/encrypt";

const state={
    password:'',
    aes:{
        key:'',
        iv:'',
    },
    content:{
        lists:[],
        currentId:null
    },
    history:{}
}
const getters={
    currentContent(state){
        if(state.content.currentId===null)
            return null;
        return {
            ...state.content.lists.find(item=>item.id===state.content.currentId)
        }
    },
    isLogin(state){
        return state.aes.key!==''&&state.aes.iv!=='';
    }
}
const mutations={
    //修改密码库内容
    modifyContent(state,editInfo){
        const originInfo = state.content.lists.find(item=>item.id===editInfo.id);
        let hasEdited=false;
        if(originInfo.name!==editInfo.name){
            hasEdited=true;
            mutations.addHistory(state,`名称为[${originInfo.name}]的密码库修改为[${editInfo.name}]`);
            originInfo.name=editInfo.name;
        }
        if(originInfo.value!==editInfo.value){
            hasEdited=true;
            mutations.addHistory(state,`名称为[${originInfo.name}]的密码库内容进行了修改`);
            originInfo.value=editInfo.value;
        }
        hasEdited&&DataPersistence.modifyContent(originInfo);
    },
    //增加密码库
    addContent(state){
        const id=nanoid(10);
        const time=dayjs(Date.now()).format("YYYY-MM-DD HH:mm:ss");
        const name=`未命名[${time}]`;
        const obj={
            id, name, 'value':'', 'createTime':time
        }
        state.content.lists.unshift(obj);
        state.content.currentId=id;
        DataPersistence.addContent(obj);
        mutations.addHistory(state,`新建了名称为[${name}]的密码库`);
    },
    //登陆成功之后初始化加密数据
    unlockInit(state,password){
        state.aes.key=md5(sha512(password).toString()).toString();
        const {key,iv}=state.aes;
        DataPersistence.initDataDB(key,iv);
        const {content,history}=DataPersistence.getHistoryData(key,iv);
        content.sort((a,b)=>a.createTime>=b.createTime?-1:1);
        state.content.lists=content;
        state.history=history;
    },
    //修改密码
    modifyPassword(state,password){
        state.aes.key=md5(sha512(password).toString()).toString();
        DataPersistence.modifyPassword(sha256(password).toString());
        DataPersistence.initDataDB(state.aes.key,state.aes.iv);
        DataPersistence.modifyWholeHistory(state.history);
        DataPersistence.modifyWholeContent(state.content.lists);
        mutations.addHistory(state,'修改了登陆密码');
    },
    //添加操作历史记录
    addHistory(state,text){
        const timestamp=Date.now();
        const day=dayjs(timestamp).format('YYYY-MM-DD');
        const time=dayjs(timestamp).format('HH:mm:ss');
        text=`[${time}]：${text}`;
        if(state.history[day]!==undefined){
            state.history[day].push(text);
        }else{
            state.history[day]=[text];
        }
        DataPersistence.addHistory(day,text);
    },
    deleteContentById(state,{name,id}){
        state.content.lists=state.content.lists.filter(item=>item.id!==id);
        DataPersistence.deleteContentByI(id);
        mutations.addHistory(state,`删除了名称为[${name}]的密码库`);
    }
}
const actions={
    async exportData(context,{path,password}){
        return DataPersistence.exportData(path,password,context.state.content.lists);
    },
    async importData(context,{path,password}){
        return await new Promise((resolve, reject)=>{
            DataPersistence.importData(path)
                .then(data=>{
                    try{
                        if(sha256(password).toString()!==data.password)
                            return reject('密码错误')
                        const key=md5(sha512(password).toString()).toString();
                        const iv=data.iv;
                        const time=dayjs(Date.now()).format("YYYY-MM-DD HH:mm:ss");
                        data.content.forEach(v=>{
                            context.state.content.lists.push({
                                id:nanoid(10),
                                name:aesDecrypt(v.name,{key,iv}),
                                value:aesDecrypt(v.value,{key,iv}),
                                createTime:time
                            })
                        });
                        context.state.content.lists.sort((a,b)=>a.createTime>=b.createTime?-1:1);
                        DataPersistence.saveContent(context.state.content.lists);
                        context.commit('addHistory',`导入了${data.content.length}条数据`);
                        resolve("数据导入成功");
                    }catch (e) {
                        context.commit('addHistory','数据导入失败');
                        reject('导入失败')
                    }
                }).catch(err=>{
                    reject(err);
            })
        })
    }
}
export default new createStore({
    state,
    getters,
    mutations,
    actions
})

